package service

import (
	"context"
	"k8s-dash/utils"
	coreV1 "k8s.io/api/core/v1"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type namespace struct{}

var Namespace namespace

type NamespaceResp struct {
	Total int                `json:"total"`
	Items []coreV1.Namespace `json:"items"`
}

// GetNSList 获取ns列表
func (n *namespace) GetNSList(filterName string, limit, page int) (ns *NamespaceResp, err error) {
	namespaceList, err := utils.K8sClient.K8sClient.CoreV1().Namespaces().List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	//封装数据
	selectData := &dataSelector{
		GenericDataList: n.toCells(namespaceList.Items),
		DataSelectQuery: &DataSelectorQuery{
			Filter: &FilterQuery{filterName},
			Paginate: &PageQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	data := selectData.Filter()
	total := len(data.GenericDataList)
	cells := data.Sort().Paginate()
	nss := n.FromCells(cells.GenericDataList)
	return &NamespaceResp{
		Total: total,
		Items: nss,
	}, nil

}

// CreateNS 创建ns
func (n *namespace) CreateNS(name string) error {
	ns := &coreV1.Namespace{
		ObjectMeta: metaV1.ObjectMeta{
			Name: name,
		},
		TypeMeta: metaV1.TypeMeta{},
		Spec:     coreV1.NamespaceSpec{},
		Status:   coreV1.NamespaceStatus{},
	}
	_, err := utils.K8sClient.K8sClient.CoreV1().Namespaces().Create(context.TODO(), ns, metaV1.CreateOptions{})
	if err != nil {
		return err
	}
	return nil
}

// GetNSDetail 获取ns详情
func (n *namespace) GetNSDetail(name string) (*coreV1.Namespace, error) {
	ns, err := utils.K8sClient.K8sClient.CoreV1().Namespaces().Get(context.TODO(), name, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return ns, nil
}

// DeleteNS 删除ns
func (n *namespace) DeleteNS(name string) error {
	err := utils.K8sClient.K8sClient.CoreV1().Namespaces().Delete(context.TODO(), name, metaV1.DeleteOptions{})
	if err != nil {
		return err
	}
	return nil
}

// 类型转换的方法 coreV1.pod => DataCell,DataCell => coreV1.pod
func (p *namespace) toCells(nodes []coreV1.Namespace) []DataCell {
	cells := make([]DataCell, len(nodes))
	for i := range nodes {
		cells[i] = nsCell(nodes[i])
	}
	return cells
}

func (p *namespace) FromCells(cells []DataCell) []coreV1.Namespace {
	nodes := make([]coreV1.Namespace, len(cells))
	for i := range cells {
		nodes[i] = coreV1.Namespace(cells[i].(nsCell))
	}
	return nodes
}
